package net.homelinux.chaoswg.io.renga.core.gui.operations;

import javax.swing.JOptionPane;

import net.homelinux.chaoswg.io.renga.core.gui.DrawingArea;
import net.homelinux.chaoswg.io.renga.core.gui.operations.helper.Connection;
import net.homelinux.chaoswg.io.renga.core.gui.operations.visualisations.NamedBlockVisualisation;
import net.homelinux.chaoswg.io.renga.core.registries.VariableRegistry;

import org.jdom.Element;

public class VariablePutOperation extends Operation {
    private String name = null;
    
    public VariablePutOperation () {
        this.visualisation = new NamedBlockVisualisation (0,0,32,32,"");
        
        this.inputs = 1;
        this.outputs = 1;
        
        connections = new Connection [1];
        connections[0] = new Connection ();
        
        this.visualisation.setInputs(1);
        this.visualisation.setOutputs(0);
    }

    @Override
    public Object apply(final int i) {
        if (i >= outputs) {
            return null;
        }
        
        result = connections[i].getResult();

        return result;
    }

    public void setName (final String name) {
        final VariableRegistry vr = VariableRegistry.getVariableRegistry();
        
        vr.removeVariablePut(this.name);
        
        vr.setVariablePut (name, this);
        ((NamedBlockVisualisation)visualisation).setName(name);
        this.name = name;
        
    }
    
    public String getName () {
        return this.name;
    }
    
    @Override
    public void prepareForRemoval () {
        super.prepareForRemoval();
        VariableRegistry.getVariableRegistry().removeVariablePut(this.name);
    }
    
    public String toString () {
        return this.name;
    }

    @Override
    public String getDoubleClickActionName() {
        return "Set Name";
    }

    @Override
    public void doubleClick(final DrawingArea dv) {
        do {
            name = JOptionPane.showInputDialog(dv, "Please enter name for binding", this.getName ());
        } while (name == null || name.equals(""));
        
        this.setName(name);
    }

    public Element writeYourself () {
        final Element toReturn = super.writeYourself();
        if (name != null)  {
            final Element tmp = new Element ("name");
            tmp.setText(name);
            toReturn.addContent(tmp);
        }
        return toReturn;
    }
}
